<template>
  <el-select v-model="id" clearable placeholder="选择学期" @change="handleChange" filterable >
    <el-option
      v-for="item in list"
      :key="item.term"
      :label="item.term"
      :value="item.term"
    />
  </el-select>

</template>
<script setup lang="ts">
import http from '@/api/js/http.ts'
import {ref,watch,defineProps,defineEmits,onMounted} from 'vue'

const list = ref<ITerm[]>([]);
const id = ref<string|null>('');

const props =  defineProps({
  modelValue:{
    type:String,
    required:true
  },
  type:{
    type:String,
    default:''
  }
});

const emits =  defineEmits(['update:modelValue','updateLabel']);

watch(()=>props.modelValue,(newVal)=>{
  id.value = newVal;
});


onMounted(()=>{
  id.value = props.modelValue;

  http.get<IList<ITerm>>("/term/list").then((res)=>{
    let collegeList = res.data?.list;
    if(collegeList){
      list.value = collegeList;
    }

    if(id.value == null){
        if(list.value.length == 1){
          id.value = list.value[0].term;
          emits('update:modelValue', id.value);
        }
    } 
  });

   
});


function  handleChange(theValue:string) {
      
      emits('update:modelValue', theValue);
      
      var label = '';
      list.value.forEach(ele=>{
        if(ele.term == theValue){
          label = ele.term;
        }
      });

      emits('updateLabel', label);
    }

</script>
